package com.yunao.web.mail.impl;

import com.alibaba.fastjson.JSONObject;
import com.yunao.commons.enums.ResultEnum;
import com.yunao.commons.utils.ResultVOUtil;
import com.yunao.commons.vo.ResultVO;
import com.yunao.web.mail.QRcodeService;
import com.yunao.web.utils.WechatUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

@Service
public class QRcodeServiceImpl implements QRcodeService {
    private Logger logger = LoggerFactory.getLogger(QRcodeServiceImpl.class);
    private HttpClient client = new DefaultHttpClient();
    @Override
    public ResultVO<String> qRcode(String accessToken, String userid) {
        String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token="+accessToken;

        HttpPost post = new HttpPost(url);
        post.setHeader("Content-Type", "application/json");
        post.addHeader("Authorization", "Basic YWRtaW46");

        String result = "";
        try {
            int seconds = 60*60;//二维码有效时间 seconds
            String name = "QR_STR_SCENE";//参数类型 name
            String str = userid;//参数内容 str

            //JSON参数
            StringEntity s = new StringEntity("{\"expire_seconds\": "+seconds+", \"action_name\": \""+name+"\", \"action_info\": {\"scene\": {\"scene_str\": \""+str+"\"}}}", "utf-8");
            s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            post.setEntity(s);

            // 发送请求
            HttpResponse httpResponse = client.execute(post);

            // 获取响应输入流
            InputStream inStream = httpResponse.getEntity().getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    inStream, "utf-8"));
            StringBuilder strber = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null)
                strber.append(line + "\n");
            inStream.close();

            result = strber.toString();
//            System.out.println(result);

            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                logger.info("请求服务器成功，做相应处理");

            } else {
                logger.info("请求服务端失败");

            }
        } catch (IOException e) {
            logger.error(e.getMessage());
//            e.printStackTrace();
        }
        JSONObject parse = (JSONObject)JSONObject.parse(result);
        String ticket = (String)parse.get("ticket");

        try {
            ticket = WechatUtils.urlEncode(ticket);
            String turl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + ticket;
            return ResultVOUtil.success(turl);
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
        return ResultVOUtil.error(ResultEnum.WECHAT_ACCESS_TOKEN_ERROR);
    }
}
